package conf

import (
	"os"
	"github.com/creamdog/gonfig"
	"sync"
	"github.com/funlake/gopkg/utils/log"
)

//路由不存在
const REQUEST_ROUTE_NOT_EXISTS = 4001
//请求超时
const REQUEST_TIMEOUT  = 4002
//路由无法转发
const REQUEST_ROUTE_ERROR  = 4004
//用户无权限请求
const REQUEST_NO_PERMISSION  = 4003
//用户请求被限流
const REQUEST_RATE_LIMIT = 4006
//access_token无效
const REQUEST_INVALID_ACCESS_TOKEN  = 4007
//服务暂停
const REQUEST_SERVICE_TEMPORARY_DOWN  = 4008
//merge请求解析错误
const REQUEST_MERGE_PARSE_ERROR = 4040
//sign验签失败
const REQUEST_MERGE_SIGN_ERROR = 4041
//网关同时请求量超标
const REQUEST_MAX_REACH_ERROR = 4051
//后端返回空
const REQUEST_EMPTY_RESULT = 4052

var scc *Config
var sccSync sync.Once
var env = os.Getenv("GATEWAY_ENV")
func InitConfig() {
	sccSync.Do(func() {
		//lib.LogInfo("Init config file")
		if env == "" {
			env = "prod"
		}
		scc = &Config{JsonCfg : map[string] gonfig.Gonfig{},env:env}
		//scc.Init()
	})
}
func GetConfig() *Config {
	InitConfig()
	return scc
}

type Config struct {
	//StatusCode gonfig.Gonfig
	sync.RWMutex
	JsonCfg map[string] gonfig.Gonfig
	env string
}

//func (this *Config) Init() {
//	this.Load("status")
//	this.Load("plugin")
//}
func (this *Config) Load(cfg string) bool {
	sf, err := os.Open("conf/"+cfg+".json")
	defer sf.Close()
	if err != nil {
		//error
		return false
	}
	config, err := gonfig.FromJson(sf)
	if err != nil {
		log.Error(err.Error())
		return false
	}
	this.JsonCfg[cfg] = config
	return true
}
func (this *Config) Get(cfg string) gonfig.Gonfig{
	this.Lock()
	defer this.Unlock()
	if this.JsonCfg[cfg] == nil {
		this.Load(cfg)
	}
	//r , err := this.JsonCfg[cfg].GetString(k,"")
	//if  err != nil{
	//	return ""
	//}
	return  this.JsonCfg[cfg]
}

func (this *Config) GetEnvInt(key string) (int) {
	app := this.Get("app")
	if app != nil {
		v, err := app.GetInt(env+"/"+key, "")
		if err != nil {
			log.Error(err.Error())
		}
		return v
	}
	return 0
}
func (this *Config) GetEnvString(key string) (string) {
	app := this.Get("app")
	if app != nil {
		v, err := this.Get("app").GetString(env+"/"+key, "")
		if err != nil {
			log.Error(err.Error())
		}
		return v
	}
	return ""
}

func (this *Config) GetEnv() string{
	return this.env
}
//func (this *Config)  GetStatusCode(code string)  string{
//	return this.Get("status", code)
//}
//
//func (this *Config)  GetAppConfig(code string)  string{
//	return this.Get("app", code)
//}